#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h> 
#include <errno.h>

#define BUFSIZE 512
#define NPACK 10

void error(char *msg)
{
    perror(msg);
    exit(0);
}

int main(int argc, char *argv[])
{
    int sockfd, portno;

    struct sockaddr_in  serv_addr;
    struct hostent      *server;
    socklen_t           addrlen;

    char buffer[BUFSIZE+1];
    if (argc < 3) {
       fprintf(stderr,"usage %s hostname port\n", argv[0]);
       exit(0);
    }
    portno = atoi(argv[2]);
    if ((sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
        error("ERROR opening socket");
    }
    if ((server = gethostbyname(argv[1])) == NULL) {
        fprintf(stderr,"ERROR, no such host\n");
        exit(0);
    }

    bzero((char *) &serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    bcopy((char *)server->h_addr_list[0], 
         (char *)&serv_addr.sin_addr.s_addr,
         server->h_length);
    serv_addr.sin_port = htons(portno);

    addrlen = sizeof(serv_addr);
    for (int i = 0; i < NPACK; ++i) {
            printf("Sending packet %d\n", i);
            sprintf(buffer, "This is packet %d", i);
            if (sendto(sockfd, buffer, BUFSIZE, 0, (struct sockaddr *) &serv_addr, addrlen) < 0) {
                error("send packet error");
            }
    }

    return 0;
}
